import time
import traceback
import logging
import os

# from info_config import mysql_dbname
from info_config import prometheus_url
from info_config import time_interval
from info_config import check_cnt
from info_config import mysql_prometheus_metrics_name
from info_config import con_timeout

from tool_util import push_simple_metric
from tool_util import mysql_create_conn
from tool_util import get_mysql_server_id
from tool_util import get_rds_mysql_resource_info


global_mysql_server_id = {}

# Get the current script path
script_path = os.path.dirname(os.path.abspath(__file__))
log_file = os.path.join(script_path, "rds_mysql_master_slave_switch.log")

logging.basicConfig(
    filename=log_file,
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s",
)


def master_switch_monitor(mysql_info):
    id = mysql_info[0]
    name = mysql_info[1]
    mysql_host = mysql_info[2].get("host")
    mysql_port = int(mysql_info[2].get("port"))
    conn = mysql_create_conn(mysql_host, mysql_port, timeout=con_timeout)
    if conn is None:
        return
    current_master_id = get_mysql_server_id(conn)
    if current_master_id is None:
        return
    master_server_id = global_mysql_server_id.get(id)
    if master_server_id is None:
        global_mysql_server_id.update(
            {id: {"old_master_server_id": current_master_id, "state_cnt": 0, "state": 0}}
        )
        return
    old_master_server_id = master_server_id.get("old_master_server_id")
    state_cnt = master_server_id.get("state_cnt")
    state = master_server_id.get("state")
    if current_master_id != old_master_server_id:
        global_mysql_server_id.get(id).update({"state_cnt": state_cnt + 1})
        global_mysql_server_id.get(id).update({"state": 1})
        state = 1

    if state == 1 and state_cnt >= check_cnt:
        global_mysql_server_id.get(id).update(
            {"old_master_server_id": current_master_id}
        )
        global_mysql_server_id.get(id).update({"state": 0})
        global_mysql_server_id.get(id).update({"state_cnt": 0})

    push_simple_metric(
        f"{mysql_prometheus_metrics_name}", state, id, name, gateway_url=prometheus_url
    )


def master_switch_monitor_all():
    mysql_info_list = get_rds_mysql_resource_info()
    while True:
        for mysql_info in mysql_info_list:
            try:
                logging.info(f"start monitor {mysql_info}")
                master_switch_monitor(mysql_info)
            except Exception as e:
                logging.error("An error occurred", exc_info=True)
        time.sleep(time_interval)


def main():
    master_switch_monitor_all()


if __name__ == "__main__":
    main()
